package com.example.tutorial.java.concurrent.thread;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 测试Executors主要方法
 *
 * @author chenpenghui
 * @date 2021-3-10
 */
public class ExecutorsTest {
    public static void main(String[] args) {

        scheduled();

    }

    private static void scheduled() {
        int num = 2;
        ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(num);
        System.out.println(LocalDateTime.now() + ", start");
        for (int i = 0; i < num; i++) {
            // 任务启动延迟3s后执行一次
            scheduled.schedule(() -> {
                System.out.println("schedule: " + LocalDateTime.now());
                System.out.println("schedule: " + Thread.currentThread().getName());
            }, 3L, TimeUnit.SECONDS);
        }

        // 任务启动延迟5s后，首个任务开始执行，每隔3s开启一个任务，不管上一个任务是否执行完
        scheduled.scheduleAtFixedRate(() -> {
            System.out.println("scheduleAtFixedRate: " + LocalDateTime.now());
            System.out.println("scheduleAtFixedRate: " + Thread.currentThread().getName());
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 5L, 3L, TimeUnit.SECONDS);

        // 任务启动延迟5s后，首个任务开始执行，上个任务执行完后间隔3s下个任务才开始执行
        scheduled.scheduleWithFixedDelay(() -> {
            System.out.println("scheduleWithFixedDelay: " + LocalDateTime.now());
            System.out.println("scheduleWithFixedDelay: " + Thread.currentThread().getName());
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 5L, 3L, TimeUnit.SECONDS);

        System.out.println(LocalDateTime.now() + ", end");
    }

    private static void cached() {
        // 创建指定数量的缓存线程, 线程空闲60s后销毁
        int num = 4;
        ExecutorService cached = Executors.newCachedThreadPool();
        for (int i = 0; i < num; i++) {
            cached.execute(() -> System.out.println(Thread.currentThread().getName()));
        }
    }

    private static void fixed() {
        // 创建指定数量的线程
        int num = 3;
        ExecutorService fixed = Executors.newFixedThreadPool(num);
        for (int i = 0; i < num; i++) {
            fixed.execute(() -> System.out.println(Thread.currentThread().getName()));
            if (fixed.isShutdown()) {
                fixed.shutdownNow();
            }
        }
    }

    private static void single() {
        // 创建单个线程
        ExecutorService single = Executors.newSingleThreadExecutor();
        single.execute(() -> System.out.println(Thread.currentThread().getName()));
        if (!single.isShutdown()) {
            single.shutdown();
        }
    }


}
